package com.study.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.dto.Result;
import com.study.entity.ShopType;
import com.study.mapper.ShopTypeMapper;
import com.study.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.study.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryShopTypeList() {
        //从Redis中查询类型数据
        String shopType = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);

        //如果Redis中有数据则返回数据到客户端
        if(StrUtil.isNotBlank(shopType)){
            return Result.ok(JSONUtil.toList(shopType,ShopType.class));
        }
        //如果Redis中没有数据则查询数据库
        List<ShopType> shopTypeDataList = query().select().orderByAsc("sort").list();


        //数据保存到Redis中
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,JSONUtil.toJsonStr(shopTypeDataList));

        //返回数据到客户端
        return Result.ok(shopTypeDataList);
    }
}
